/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from 'react';
import { Upload, Icon, Button, Modal, Table, Select, Row, Col } from 'antd';
import { connect } from 'dva';
import classNames from 'classnames';
import styles from './FileImport.less';
import { isArray } from 'lodash';

const { Option } = Select;
const { Dragger } = Upload;
@connect(({ loading }) => ({
    uploading: loading.effects['address/importExcel'],
    parsing: loading.effects['address/parseExcel'],
}))
class FileImport extends Component {
    static defaultProps = {
        onImport: () => {
        }
    };

    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            selected: [],
            fileList: [],
            dataSource: [],
        };
        this.options = ['所有', '姓名', '电话', '公司名称', '省市区', '详细地址', '商品名称', '商品规格', '备注', '第三方订单编号', ''];
        this.columns = [];
    }

    // 解析
    onImport = () => {
        const { dispatch, onImport } = this.props;
        const { selected } = this.state;
        dispatch({
            type: 'address/parseExcel',
            payload: {
                info: JSON.stringify(selected),
                file: this.uploadedFile,
            },
        })
            .then(data => {
                this.setState(
                    {
                        visible: false,
                    },
                    () => {
                        const formated = data.map(item => {
                            const {
                                item_note,
                                package_note,
                                package_name,
                                weight: package_weight,
                                shipping_name: name,
                                shipping_mobile: mobile,
                                shipping_province: province,
                                shipping_city: city,
                                shipping_district: district,
                                shipping_address: address,
                                third_order_id,
                                complete,
                                company
                                } = item;
                            return {
                                name,
                                mobile,
                                province,
                                city,
                                district,
                                address,
                                package_note,
                                package_name,
                                package_weight,
                                item_note,
                                complete,
                                company,
                                third_order_id,
                                excel:true
                            };
                        });
                        onImport(formated);
                    }
                );
            })
            .catch(() => {
                this.setState({
                    visible: false,
                });
            });
    };

    onCancel = () => {
        this.setState(
            {
                visible: false,
            },
            () => {
                this.props.dispatch({
                    type: 'global/setIntercept',
                    payload: false,
                });
            }
        );
    };

    onBeforeUpload = file => {
        this.setState({
            fileList: [file],
        });
        return false;
    };

    // 跳转帮助页
    onToHelp = e => {
        e.stopPropagation();
        window.open('//m.kuaidihelp.com/help/wzg_help_0', '_blank');
    };

    // 上传
    onUpload = e => {
        e.stopPropagation();
        const { dispatch,onImport } = this.props;
        const { fileList } = this.state;
        const formData = new FormData();
        let txt = false;
        fileList.forEach(file => {
            if (file.name.indexOf('.txt') != -1) {
                txt = true;
                formData.append('text', file);
            } else {
                formData.append('excel', file);
            }
        });
        dispatch({
            type: 'address/importExcel',
            txt,
            payload: formData,
        }).then(data => {
                this.setState(
                    {
                        fileList: [],
                        visible: txt ? false : true,
                    },
                    () => {
                        let { file, list } = data;
                        if (txt) {
                            list = data;
                          const formated =  list.map(item => {
                                const {
                                    item_note,
                                    package_note,
                                    package_name,
                                    weight: package_weight,
                                    shipping_name: name,
                                    shipping_mobile: mobile,
                                    shipping_province: province,
                                    shipping_city: city,
                                    shipping_district: district,
                                    shipping_address: address,
                                    third_order_id,
                                    complete,
                                    } = item;
                                return {
                                    name,
                                    mobile,
                                    province,
                                    city,
                                    district,
                                    address,
                                    package_note,
                                    package_name,
                                    package_weight,
                                    item_note,
                                    third_order_id,
                                    complete,
                                    excel:true
                                };
                            });
                            onImport(formated);
                            return;
                        }

                        if (file && isArray(list) && list.length) {
                            this.uploadedFile = file;
                            const dataSource = [];
                            const selected = list[0];
                            list.map((item, index) => {
                                if (index > 0) {
                                    const rowData = {};
                                    item.map((iitem, iindex) => {
                                        rowData[`${iindex}`] = iitem;
                                        rowData.key = `${index}`;
                                    });
                                    dataSource.push(rowData);
                                }
                            });
                            this.createColumns(selected);
                            this.setState({
                                selected,
                                dataSource,
                            });
                            dispatch({
                                type: 'global/setIntercept',
                                payload: true,
                            });
                        }
                    }
                );
            }
        )
        ;
    }
        ;

// 切换选择
    onSelectChange(index, value) {
        const selected = [...this.state.selected];
        selected.splice(index, 1, value);
        this.setState({
            selected,
        });
    }

// 表格头部
    renderTitle(index) {
        const defaultValue = this.state.selected[index];
        const selectCls = classNames(defaultValue ? styles.select : styles.unimport);
        return (
            <Select
                className={selectCls}
                defaultValue={defaultValue}
                style={{ width: 140 }}
                onChange={this.onSelectChange.bind(this, index)}
            >
                {this.options.map(item => (
                    <Option key={item} value={item}>
                        {item == '所有' ? '所有信息' : item || '不导入'}
                    </Option>
                ))}
            </Select>
        );
    }

// 表格列
    renderCol(index, value) {
        return <span style={{ color: !this.state.selected[index] ? '#ccc' : '' }}>{value}</span>;
    }

// 创建表格columns
    createColumns(selected) {
        this.columns = [];
        const selectedLength = selected.length;
        const width = 150;
        selected.map((_, index) => {
            this.columns.push({
                width,
                title: this.renderTitle.bind(this, index),
                dataIndex: `${index}`,
                key: `${index}`,
                render: this.renderCol.bind(this, index),
            });
        });
        this.width = width * selectedLength;
    }

    render() {
        const { uploading, parsing ,onlyimport=false} = this.props;
        const { fileList, visible, dataSource } = this.state;
        const closable = !uploading && !parsing;
        const hasFile = fileList.length;
        return (
            <>
            <Dragger
                showUploadList={false}
                withCredentials
                fileList={fileList}
                accept=".txt,.xlsx,.xls,csv"
                name="file"
                multiple={false}
                beforeUpload={this.onBeforeUpload}
            >
                <div className={styles.inner}>
                    <div>
              <span className={styles.bar}>
                <Button type={hasFile ? `dashed` : 'primary'} icon="file-text">
                    {hasFile
                        ? fileList.map(item => (
                        <span key={item.name} className="ant-upload-text">
                          {item.name}
                        </span>
                    ))
                        : '请选择要导入的excel或txt文件'}
                </Button>
              </span>
                        <Button
                            icon="upload"
                            loading={uploading}
                            disabled={!hasFile}
                            type="primary"
                            onClick={this.onUpload}
                        >
                            导入
                        </Button>
                        <Button
                            type="link"
                            style={{ paddingRight: 0 }}
                            icon="question-circle"
                            onClick={this.onToHelp}
                        >
                            更多导入帮助
                        </Button>
                    </div>
                    {
                        !onlyimport && ( <div className={styles.tips}>
                            <p ><span>如您导入的文档中含商品信息和备注信息，将以导入的为准</span></p>
                            <p>最新增加支持：导入“<span>姓名电话地址</span>”在一列表格内的文档，导入后选择对应“<span>所有信息</span>”即可</p>
                            <p style={{ marginTop: 24 }}>如何导入生鲜包裹：</p>
                            <p>
                                文档导入时，如需生成的订单为生鲜包裹，请编辑物品名称为：<span>生鲜：商品名称</span>
                                ；如：<span>生鲜：进口牛肉</span>

                            </p>
                            <p>申通生鲜打印需要使用：1、申通通用大客户账号里面充入的生鲜单号；2、申通生鲜专用绿色面单纸</p>
                            <p style={{ marginTop: 24 }}>txt文档的格式要求：</p>
                            <p>
                                每行添加一条信息，按姓名、电话、地址、物品类型的顺序输入（用逗号或空格隔开）
                                <br />
                                <span>示例：王某某 13312345678 上海市长宁区通协路269号 日用品</span>
                            </p>
                        </div>)
                    }

                </div>
            </Dragger>
            <Modal
                destroyOnClose
                maskClosable={false}
                centered
                visible={visible}
                onOk={this.onImport}
                title={
            <div>
              文档导入
              <span style={{ color: '#f72f5f' }}>
                （已自动匹配对应信息，如有匹配错误，请选择手动修改）
              </span>
            </div>
          }
                okButtonProps={{ loading: parsing, icon: 'save' }}
                width="80%"
                style={{ minWidth: '80%' }}
                okText="保存"
                cancelText={closable ? '取消' : ''}
                closable={closable}
                onCancel={this.onCancel}
            >
                <Table
                    dataSource={dataSource}
                    pagination={false}
                    columns={this.columns}
                    scroll={{ x: this.width }}
                />
                <div style={{ fontWeight: 'bold', textAlign: 'center', paddingTop: 16 }}>... ...</div>
            </Modal>
            </>
        );
    }
}

export default FileImport;
